﻿package org.ilanchong.droidcontroller;

import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import org.ilanchong.droidcontroller.socket.DroidClient;
import org.ilanchong.droidcontroller.socket.MyDatagramSocket;

public class DroidController {

	private static String createRandomAuthCode() {
		String authCode = "";
		java.util.Random random = new java.util.Random(); 
		for(int i = 0; i < 4; i ++){
			authCode += random.nextInt(10);
		}
		return authCode;
	}

	public static void sendCommond(ComputerInfo computer, int port, String commond) {
		DroidClient client = null;

		if (computer == null) {
			return;
		}

		try {
			client = new DroidClient(computer.getIP(), port);
			client.setTimeOut(Utils.CONNECT_TIMEOUT);
			client.sendCommand(commond);

		} catch (UnknownHostException e) {

		} catch (IOException e) {

		} finally {
			try {
				client.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static SearchResultInfo getIPHostname(String broadcast_ip, String localIP, int broadcast_port, String command) {
		SearchResultInfo resInfo = new SearchResultInfo(false, "", null);

		MyDatagramSocket myDatagramSocket = null;
		try {
			myDatagramSocket = new MyDatagramSocket();
			myDatagramSocket.setSoTimeout(Utils.CONNECT_TIMEOUT);

			myDatagramSocket.sendMessage(InetAddress.getByName(broadcast_ip), broadcast_port, command);
			//received the ip and hostname
			String str = myDatagramSocket.receiveMessage();
			
			String ips_hostname = "";
			if (str != null && !"".equals(str.trim())) {
				ips_hostname = str.trim();
				int _i = ips_hostname.lastIndexOf("#");

				resInfo.setComputer(new ComputerInfo());
				resInfo.getComputer().setHostName( ips_hostname.substring(_i + 1));
				resInfo.getComputer().setIP( Utils.getPriorityIP(ips_hostname.substring(0, _i), localIP));
				resInfo.setResult(true);
				resInfo.setMessage("");
			} else {
				resInfo.setResult(false);
				resInfo.setMessage("无法 接收到IP, 接收到IP 为空");
			}
			return resInfo;
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (myDatagramSocket != null && !myDatagramSocket.isClosed())
				myDatagramSocket.close();
		}
		return null;
	}
}
